import { Button, Form, Input, Modal, Table, message, Breadcrumb} from "antd";
import { useEffect, useState } from "react";
import { getUsers, getAddUsers } from "../../service/index";
import './user.css'
function User(props) {
  const [dataSource, setDataSource] = useState([]);
  const [columns, setColumns] = useState([]);
  const [boolean, setBooolean] = useState(true);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [total,setTotal]=useState(0) 
  const [pagenum,setPagenum]=useState(1)
  const [pagesize]=useState(5)
  const [pagination,setPagination]=useState({})
  useEffect(() => {
    const token = sessionStorage.getItem("token");
    console.log('拿到的token是', token)
    if (!token) {
      // 如果未登录（没有token），重定向到登录页面
      props.history.push("/login");
    }
    setPagination(
      {
        pagenum: pagenum, //当前页码
        pageSize:pagesize, // 每页数据条数
        total:total, // 总条数
        onChange:handlePageChange, //改变页码的函数
      }
    )
    if (boolean) {
      const queryInfo={pagenum:pagenum,pagesize:pagesize}
      getUsers(queryInfo).then((res) => {
        console.log(res);
        setDataSource(res.data.users);
        setTotal(res.data.total)
        setColumns([
          {
            title: "用户名",
            dataIndex: "username",
            key: "1",
          },
          {
            title: "邮箱",
            dataIndex: "email",
            key: "2",
          },
          {
            title: "电话",
            dataIndex: "mobile",
            key: "3",
          },
          {
            title: "角色",
            dataIndex: "role_name",
            key: "4",
          },
        ]);
      });
    }
    setBooolean(false);
  }, [boolean,dataSource,pagenum,pagesize,total]);


  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    form.validateFields().then((values) => {
      getAddUsers(values).then((res) => {
        if (res.meta.status === 201) {
          message.info("添加用户成功");
          setIsModalVisible(false);
          setBooolean(true);
        } else {
          message.info("添加用户失败");
          setIsModalVisible(false);
        }
      });
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handlePageChange = (pagenum) => {
    console.log(pagenum);
    setPagenum(pagenum)
    setBooolean(true);
  }

  return (
    <div className="userBody">
      <div className="userBread">
        <Breadcrumb>
          <Breadcrumb.Item>首页</Breadcrumb.Item>
          <Breadcrumb.Item>用户管理</Breadcrumb.Item>
          <Breadcrumb.Item>用户列表</Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <div>
        <Button type="primary" onClick={showModal} className="userButton">
          添加角色
        </Button>
        {isModalVisible && (
          <Modal
            title="添加角色"
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <Form
              name="basic"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              autoComplete="off"
              form={form}
              preserve={false}
            >
              <Form.Item
                label="用户名"
                name="username"
                rules={[
                  { required: true, message: "Please input your username!" },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="密码"
                name="password"
                rules={[
                  { required: true, message: "Please input your password!" },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="邮箱"
                name="email"
                rules={[
                  { required: true, message: "Please input your password!" },
                ]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="手机"
                name="mobile"
                rules={[
                  { required: true, message: "Please input your password!" },
                ]}
              >
                <Input />
              </Form.Item>
            </Form>
          </Modal>
        )}
      </div>
      <Table
        rowKey={(record) => record.id}
        bordered
        dataSource={dataSource}
        columns={columns}
        pagination={pagination}
     ></Table>
    </div>
  );
}
export default User;
